package cn.edu.jnu.supershopper;

import android.util.Log;

import androidx.annotation.NonNull;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

public class DataLoader {
    @NonNull
    public static String getHttpData(String path){
        try{
            URL url = new URL(path);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(100000);
            conn.setReadTimeout(50000);
            conn.setRequestMethod("GET");

            if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                InputStreamReader inputStreamReader = new InputStreamReader(conn.getInputStream());
                BufferedReader reader = new BufferedReader(inputStreamReader);
                String tempLine = null;
                StringBuffer resultBuffer = new StringBuffer();
                while ((tempLine = reader.readLine()) != null) {
                    resultBuffer.append(tempLine);
                    resultBuffer.append("\n");
                }
                Log.i("test data",resultBuffer.toString());

                return resultBuffer.toString();
            }
        }catch(Exception exception)
        {
            Log.e("error",exception.getMessage());
        }
        return "";
    }

    @NonNull
    public Book ParseJsonData(String JsonText)
    {
        Book book=new Book("无",1);//赋默认值，后面覆盖
        try {
            JSONObject root = new JSONObject(JsonText);
            JSONObject shop = root.getJSONObject("data");

            book.setName(shop.getString("name"));
            book.setIsbn(shop.getString("code"));
            book.setAuthor(shop.getString("author"));
            book.setAuthorlntro(shop.getString("authorIntro"));
            book.setPhotoUrl(shop.getString("photoUrl"));
            book.setPublishing(shop.getString("publishing"));
            book.setPublished(shop.getString("published"));
            book.setDescription(shop.getString("description"));
            book.setDoubanScore(shop.getString("doubanScore"));

        } catch (JSONException e) {
            e.printStackTrace();
        }
        return book;
    }
}

